<template>
    <view class="record-button c-flex_row c-align_center">
        <view class="unstart item c-flex_1" v-if='showUnStart' @click="tapRecord">
            <view class="title">
                点击开始录音
            </view>
        </view>
        <view class="recording item c-flex_1" v-else-if='showRecording' @click="tapStopRecord">
            <view class="circle-loading">
                <lj-chart :rotate='circleLoadingRotate' :size="30" :diameter='10'></lj-chart>
            </view>
            <view class="title">
                点击结束
            </view>
        </view>
        <view class="submission item c-flex_1" v-else-if='showSubmission'>
            <view class="loading"></view>
            <view class="title">
                评测中...
            </view>
        </view>
        <view class="complete item c-flex_1" v-else-if="showComplete">
            <view class="score item c-flex_1">
                <score-star :score='score' :size='26' :space='10'></score-star>
                <!-- <view class="title">
                    {{score}}
                </view> -->
            </view>
            <view class="restart item c-flex_1" @click="tapRestart">
                <view class="title">
                    再来一次
                </view>
            </view>
            <view class="next item c-flex_1" @click="tapNext(finish)">
                <view class="title">
                    {{finish? "完成": "下一句"}}
                </view>
            </view>
        </view>
        <view class="invalid" v-else>
            错误的内容
        </view>
    </view>
</template>

<script>
    import {
        checkAuthSetting
    } from '../../../common/utils/util.js';
    import {
        uploadFile,
        submitWordAnswer,
        submitAloudAnswer
    } from '../services/index.js';
    import ScoreStar from "./score-star.vue"
    const RECORD_STATUS = {
        INVALID: {
            name: "非法内容",
            value: 0
        },
        UNSTART: {
            name: "未开始",
            value: 1
        },
        RECORDING: {
            name: "录音中",
            value: 2
        },
        SUBMISSION: {
            name: "评测中",
            value: 3
        },
        COMPLETE: {
            name: "完成",
            value: 4
        }
    }
    const _MAX_RECORD_TIME = 60;
    const _recordManager = uni.getRecorderManager();
    export default {
        components: {
            ScoreStar
        },
        props: {
            type: {
                type: String,
                default: 'aloud' // aloud word
            }, // 类型 决定如何提交测评
            articleId: {
                type: String,
                default: ""
            }, // 文章id
            questionId: {
                type: String,
                default: ""
            }, // 问题id word 需要
            index: {
                type: Number,
                default: 0
            }, // index
            content: {
                type: String,
                default: ""
            }, // 录音文本内容
            total: {
                type: Number,
                default: 0
            }, // 需要录音内容总计
        },
        data: function() {
            return {
                status: RECORD_STATUS.UNSTART.value, // 状态
                recordTimeCountInterval: null, // 录音计时定时器
                recordTimeCount: _MAX_RECORD_TIME, // 录音计时

                isRecordStart: false,
                recordUrl: null,
                score: 0, // 得分
            }
        },
        watch: {
            recordUrl: function(n) {
                if (n) {
                    this.uploadRecord(n);
                }
            },
            recordTimeCount: function(n) {
                if (n == 0) {
                    this.stopRecord();
                }
            },
            content: {
                handler: function(n) {
                    this.score = 0;
                    if (n) {
                        this.status = RECORD_STATUS.UNSTART.value
                    } else {
                        this.status = RECORD_STATUS.INVALID.value
                    }
                },
                immediate: true
            },
            isRecordStart: function(n) {
                if (n) {
                    this.status = RECORD_STATUS.RECORDING.value;
                }
            }
        },
        computed: {
            finish: function() {
                return this.index >= this.total - 1
            },
            circleLoadingRotate: function() {
                let percent = (_MAX_RECORD_TIME - this.recordTimeCount) / _MAX_RECORD_TIME;
                return percent * 100;
            },
            showUnStart: function() {
                return this.status == RECORD_STATUS.UNSTART.value
            },
            showRecording: function() {
                return this.status == RECORD_STATUS.RECORDING.value
            },
            showSubmission: function() {
                return this.status == RECORD_STATUS.SUBMISSION.value
            },
            showComplete: function() {
                return this.status == RECORD_STATUS.COMPLETE.value
            }
        },
        mounted() {
            this.$nextTick(() => {
                this.authorizedCheck(res => {
                    if (res) {
                        this.onRecordWatch();
                    }
                });
            })
        },
        destroyed() {
            this.clearRecordTimeCountInterval();
        },
        methods: {
            /**
             * 录音监听
             */
            onRecordWatch() {
                _recordManager.onStart(() => {
                    console.log("record start")
                    this.isRecordStart = true;
                })
                _recordManager.onStop((res) => {
                    console.log("record stop", res)
                    this.recordUrl = res.tempFilePath;
                    this.isRecordStart = false;
                })
                _recordManager.onPause(() => {
                    console.log("record pause")
                })
                _recordManager.onResume(() => {
                    console.log("record resume")
                })
                _recordManager.onInterruptionBegin(res => {
                    console.log("record interruptionBegin")
                })
                _recordManager.onInterruptionEnd(res => {
                    console.log("record interruptionEnd")
                    _recordManager.resume();
                })
                _recordManager.onError(error => {
                    uni.showToast({
                        title: "录音错误",
                        icon: 'none'
                    })
                    this.tapRestart();
                })
            },

            /**
             * 授权检查
             * @param {Object} callback
             */
            authorizedCheck(callback) {
                // #ifdef H5
                callback(true)
                // #endif
                // #ifndef H5
                checkAuthSetting("record", (res) => {
                    if (typeof callback == 'function') {
                        callback(res);
                    }
                    if (!res) {
                        uni.showModal({
                            title: "需要功能授权",
                            content: "该功能需要您授权录音功能，是否前往设置页面授权？",
                            success: (res) => {
                                if (res.cancel) {
                                    uni.navigateBack()
                                } else {
                                    uni.openAppAuthorizeSetting()
                                }
                            }
                        })
                    }
                })

                // #endif
            },

            /**
             * 上传评测
             * @param {Object} filePath
             */
            uploadRecord(filePath) {
                uploadFile(filePath).then(res => {
                    if (this.type == 'aloud') {
                        return submitAloudAnswer(this.articleId, this.content, res, this.index + 1);
                    } else if (this.type == 'word') {
                        return submitWordAnswer(this.articleId, this.content, this.questionId, res, this.index +
                            1);
                    }
                }).then(res => {
                    this.score = res.score;
                    this.status = RECORD_STATUS.COMPLETE.value;
                }).catch(err => {
                    uni.showToast({
                        title: "评测失败",
                        icon: "none"
                    })
                    this.tapRestart();
                })
            },
            /**
             * 清空定时器
             */
            clearRecordTimeCountInterval: function() {
                if (this.recordTimeCountInterval) {
                    clearInterval(this.recordTimeCountInterval);
                    this.recordTimeCountInterval = null;
                }
            },
            /**
             * 开始录音
             */
            startRecord: function() {
                this.clearRecordTimeCountInterval();
                this.recordTimeCountInterval = setInterval(() => {
                    this.recordTimeCount--;
                }, 1000)
                this.nextStatus();
                // 开始录音
                this.recordStart();
            },

            // 录音
            recordStart() {
                _recordManager.start({
                    duration: _MAX_RECORD_TIME * 1000,
                    format: "wav"
                });
            },
            // 停止录音
            recordStop() {
                if (_recordManager) {
                    _recordManager.stop();
                } else {
                    throw new Error("_recordManager undefined")
                }
            },
            /**
             * 结束录音
             */
            stopRecord: function() {
                this.clearRecordTimeCountInterval();
                this.recordTimeCount = _MAX_RECORD_TIME;
                this.nextStatus();
                // 停止录音，上传评测
                this.recordStop();
            },
            /**
             * 状态步进
             */
            nextStatus() {
                switch (this.status) {
                    case RECORD_STATUS.COMPLETE.value:
                        this.status = RECORD_STATUS.UNSTART.value;
                        break;
                    case RECORD_STATUS.RECORDING.value:
                    case RECORD_STATUS.SUBMISSION.value:
                        this.status++;
                        break;
                    case RECORD_STATUS.UNSTART.value:
                    case RECORD_STATUS.INVALID.value:
                    default:
                        break;
                }
            },
            /**
             * 点击录音
             */
            tapRecord() {
                this.startRecord();
            },
            /**
             * 点击停止录音
             */
            tapStopRecord() {
                if (this.isRecordStart) {
                    this.stopRecord();
                }
            },
            /**
             * 点击再来一次
             */
            tapRestart() {
                this.status = RECORD_STATUS.UNSTART.value;
                this.startRecord();
            },
            /**
             * 点击下一句
             */
            tapNext(finish) {
                this.$emit("next", {
                    score: this.score,
                    finish
                })
            },
        }
    }
</script>

<style lang="scss" scoped>
    .record-button {
        height: 100%;

        .item {
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: center;
            border-radius: 15rpx;
            height: 100%
        }

        .title {
            font-size: 28rpx;
            font-weight: 700;
        }

        .unstart {
            background: #ffda17;
            color: #333;
        }

        .recording {

            background: #ff2525;
            color: #333;

            .circle-loading {
                width: 30px;
                height: 30px;
                margin-right: 20rpx;
            }

            .title {
                color: #fff;
            }
        }

        .submission {
            background: #f1f1f7;
            color: #b1b2b3;

            .loading {}

            .title {
                font-weight: 500;
            }
        }

        .complete {
            .item {
                margin-right: 15rpx;
            }

            .item:last-child {
                margin-right: 0;
            }

            .score {
                .title {
                    font-size: 42rpx;
                    color: #ff2525;
                    font-weight: 700;
                }

                .title::before {
                    content: "本句得分：";
                    font-size: 24rpx;
                }
            }

            .score::before {}

            .restart {
                background: #ffda17;
                border-radius: 10rpx;
                height: 80rpx;
            }

            .next {
                background: #ff2525;
                border-radius: 10rpx;
                height: 80rpx;
                color: #fff;
            }
        }
    }
</style>